package com.uyayo.portal.controller;

import com.uyayo.cms.entity.*;
import com.uyayo.cms.model.*;
import com.uyayo.cms.service.*;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.web.annotation.GetRequestInfo;
import com.uyayo.framework.web.model.RequestDefaultInfo;
import com.uyayo.portal.biz.CmsSiteBiz;
import com.uyayo.portal.biz.ParamBiz;
import com.uyayo.portal.exception.SiteNotFoundException;
import com.uyayo.portal.vo.*;
import com.uyayo.portal.wrap.CmsArticleWrap;
import com.uyayo.portal.wrap.CmsCommentWrap;
import com.uyayo.portal.wrap.CmsReplyWrap;
import com.uyayo.ucenter.entity.Member;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 *
 * <p>
 * Description:评论的Controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping()
public class CmsCommentController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final ParamBiz paramBiz;

	private final CmsSiteBiz cmsSiteBiz;

	private final CmsSiteService cmsSiteService;

	private final CmsChannelService cmsChannelService;

	private final CmsArticleService cmsArticleService;

	private final CmsCommentService cmsCommentService;

	private final CmsReplyService cmsReplyService;

	private final  CmsArticleLikeService cmsArticleLikeService;

	private final  CmsCommentLikeService cmsCommentLikeService;

	private final  CmsReplyLikeService cmsReplyLikeService;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final CmsTagService cmsTagService;

	private final CmsArticleCategoryService cmsArticleCategoryService;

	@Autowired
	public CmsCommentController(MessageSource messageSource, CmsArticleService cmsArticleService, CmsChannelService cmsChannelService, CmsSiteService cmsSiteService, CmsSiteBiz cmsSiteBiz, ParamBiz paramBiz, CmsCommentService cmsCommentService, CmsReplyService cmsReplyService, CmsArticleLikeService cmsArticleLikeService, CmsCommentLikeService cmsCommentLikeService, CmsReplyLikeService cmsReplyLikeService, DozerBeanMapper dozerBeanMapper, CmsTagService cmsTagService, CmsArticleCategoryService cmsArticleCategoryService) {
		this.messageSource = messageSource;
		this.cmsArticleService = cmsArticleService;
		this.cmsChannelService = cmsChannelService;
		this.cmsSiteService = cmsSiteService;
		this.cmsSiteBiz = cmsSiteBiz;
		this.paramBiz = paramBiz;
		this.cmsCommentService = cmsCommentService;
		this.cmsReplyService = cmsReplyService;
		this.cmsArticleLikeService = cmsArticleLikeService;
		this.cmsCommentLikeService = cmsCommentLikeService;
		this.cmsReplyLikeService = cmsReplyLikeService;
		this.dozerBeanMapper = dozerBeanMapper;
		this.cmsTagService = cmsTagService;
		this.cmsArticleCategoryService = cmsArticleCategoryService;
	}


	@ResponseBody
	@RequestMapping(method=RequestMethod.POST,value={"/comment"})
	public Result comment(HttpServletRequest request, @Validated CmsCommentVO cmsCommentVO, Errors errors,@GetRequestInfo RequestDefaultInfo requestInfo) {

		try {

			if (errors.hasErrors()) {
				return new Result(400,errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated()){
				String message = messageSource.getMessage("user.login",new Object[]{}, request.getLocale());
				logger.error(message);
				return new Result(5001,message);
			}
			Member member = (Member) subject.getPrincipal();
			CmsComment cmsComment = new CmsComment();
			cmsComment.setCreateTime(new Date());
			cmsComment.setMemberId(member.getId());
			cmsComment.setArticleId(cmsCommentVO.getArticleId());
			cmsComment.setIp(requestInfo.getRequestIp());
			cmsComment.setContent(cmsCommentVO.getContent());
			cmsComment.setStatus((short) 1);
			cmsCommentService.createCmsComment(cmsComment);
			return new Result(200,"评论成功！",request.getHeader("Referer"));
		}catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return new Result(400,message);
		}
	}

	@ResponseBody
	@RequestMapping(method=RequestMethod.GET,value={"/comment"})
	public Result findComment(@RequestParam(value = "pageCurrent",required = false, defaultValue = "1") Integer pageCurrent, //第几页
							@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,@Validated CmsCommentCondition cmsCommentCondition, Errors errors) {

		try {

			if (errors.hasErrors()) {
				return new Result(400,errors.getFieldError().getDefaultMessage());
			}
			CmsComment cmsComment = new CmsComment();
			cmsComment.setCreateTime(new Date());
			cmsCommentCondition.setStatus((short) 1);
			PageBean<CmsCommentBO> pageBean =cmsCommentService.selectCmsCommentListByPaging(pageCurrent,pageSize,"createTime","desc",cmsCommentCondition);

			Subject subject = SecurityUtils.getSubject();
			List<CmsCommentLike> cmsCommentLikes = new ArrayList<>();
			if(subject.isAuthenticated()){
				Member member = (Member) subject.getPrincipal();
				Example example = new Example(CmsCommentLike.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("memberId",member.getId());
				List<Long> list = pageBean.getList().stream().map(CmsComment::getId).collect(Collectors.toList());
				if(list.size()>0) {
					criteria.andIn("commentId", list);
					example.createCriteria();
					cmsCommentLikes = cmsCommentLikeService.selectByExample(example);
				}
			}

			List<CmsCommentLike> finalCmsCommentLikes = cmsCommentLikes;
			List<CmsCommentWrap> cmsCommentWraps= pageBean.getList().stream().map(cmsCommentBO -> {
				CmsCommentWrap cmsCommentWrap = dozerBeanMapper.map(cmsCommentBO,CmsCommentWrap.class);
				finalCmsCommentLikes.stream().anyMatch(cmsCommentLike -> {
					if(cmsCommentBO.getId().equals(cmsCommentLike.getCommentId()) && cmsCommentLike.getLikeType()==1){
						cmsCommentWrap.setLikeStatus(cmsCommentLike.getStatus());
					}
					if(cmsCommentBO.getId().equals(cmsCommentLike.getCommentId()) && cmsCommentLike.getLikeType()==2){
						cmsCommentWrap.setDislikeStatus(cmsCommentLike.getStatus());
					}
					return false;
				});
				return cmsCommentWrap ;
			}).collect(Collectors.toList());

			PageBean<CmsCommentWrap> cmsCommentWrapPageBean = new PageBean<>();
			cmsCommentWrapPageBean.setPageCurrent(pageBean.getPageCurrent());
			cmsCommentWrapPageBean.setPageSize(pageBean.getPageSize());
			cmsCommentWrapPageBean.setTotalCount(pageBean.getTotalCount());
			cmsCommentWrapPageBean.setTotalPage(pageBean.getTotalPage());
			cmsCommentWrapPageBean.setList(cmsCommentWraps);
			return new Result(200,"查询成功！",cmsCommentWrapPageBean);
		}catch (Exception e) {
			e.printStackTrace();
			return new Result(400,"查询失败，服务器发生异常，请管理员联系！");
		}
	}


	@ResponseBody
	@RequestMapping(method=RequestMethod.POST,value={"/comment/like"})
	public Result commentLike(HttpServletRequest request, @Validated CmsCommentLikeVO cmsCommentLikeVO, Errors errors, @GetRequestInfo RequestDefaultInfo requestInfo) {

		try {

			if (errors.hasErrors()) {
				return new Result(400,errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated()){
				String message = messageSource.getMessage("user.login",new Object[]{}, request.getLocale());
				logger.error(message);
				return new Result(5001,message);
			}
			Member member = (Member) subject.getPrincipal();
			CmsCommentLike cmsCommentLike = new CmsCommentLike();
			cmsCommentLike.setCreateTime(new Date());
			cmsCommentLike.setMemberId(member.getId());
			cmsCommentLike.setCommentId(cmsCommentLikeVO.getCommentId());
			cmsCommentLike.setLikeType(cmsCommentLikeVO.getLikeType());
			cmsCommentLike.setIp(requestInfo.getRequestIp());
			cmsCommentLike.setStatus(cmsCommentLikeVO.getStatus());
			cmsCommentService.like(cmsCommentLike);
			return new Result(200,"点赞成功！",request.getHeader("Referer"));
		}catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return new Result(400,message);
		}
	}


	@ResponseBody
	@RequestMapping(method=RequestMethod.GET,value={"/comment/like"})
	public Result findCommentLike(Long commentId ,HttpServletRequest request) {

		try {

			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated()){
				String message = messageSource.getMessage("user.login",new Object[]{}, request.getLocale());
				logger.error(message);
				return new Result(5001,message);
			}
			Member member = (Member) subject.getPrincipal();
			CmsCommentLikeCondition cmsCommentLikeCondition = new CmsCommentLikeCondition();
			cmsCommentLikeCondition.setCommentId(commentId);
			cmsCommentLikeCondition.setMemberId(member.getId());
			cmsCommentLikeCondition.setStatus((short) 1);
			List<CmsCommentLike> cmsCommentLikeList = cmsCommentLikeService.selectCmsCommentLike(cmsCommentLikeCondition);
			return new Result(200,"查询成功！",cmsCommentLikeList);
		}catch (Exception e) {
			e.printStackTrace();
			return new Result(400,"查询失败，服务器发生异常，请管理员联系！");
		}
	}
}
